import logging
from django.db.models import F, Case, When, Sum

from purchase.models import WareHouseEntry, WareHouseStats, WareHouseEntryDetail

logger = logging.getLogger("django")


def decrease_entries(objs):
    """减少入库单已付金额和状态"""
    for obj in objs:
        decrease_entry(obj)


def decrease_entry(obj):
    """减少入库单已付金额和状态"""
    WareHouseEntry.objects.filter(id=obj.entry_id) \
        .update(
        amount=F("amount") - obj.pay_amount,
        status=Case(When(total_amount__lte=F("amount"), then=1), default=0)
    )


def get_entry_stats(goods_id):
    return WareHouseStats.objects.filter(goods_id=goods_id).first()


def increase_entries_stats(objs, factor=1):
    """统计进货商品的数量和金额"""
    for obj in objs:
        increase_entry_stats(obj, factor)


def increase_entry_stats(obj, factor=1):
    """统计进货商品的数量和金额"""
    logger.info("increase_entry_stats")
    nums = WareHouseStats.objects.filter(goods_id=obj.goods_id)\
        .update(nums=F('nums') + (obj.nums * factor), total_amount=F('total_amount') + (obj.total_amount * factor))

    if nums == 0:
        results = WareHouseEntryDetail.objects.filter(goods_id=obj.goods_id).aggregate(nums=Sum('nums'), total_amount=Sum('total_amount'))
        nums = results.get('nums', 0) or 0
        total_amount = results.get('total_amount', 0) or 0
        data = {
            'goods': obj.goods,
            'nums': nums,
            'total_amount': round(total_amount, 3),
        }
        WareHouseStats.objects.create(**data)

